export function useWebEnv() {
  let env = "web"
  // #ifdef WEB
  const ua = navigator.userAgent.toLowerCase()
  if (ua.match(/MicroMessenger/i)) env = "wxWeb"
  if (ua.match(/MicroMessenger/i) && ua.match(/miniprogram/i)) env = "wxMp"
  // #endif
  return env
}

// 获取业务环境
export function useWebEvn() {
  let evn = "web"
  // #ifdef WEB
  const ua = navigator.userAgent.toLowerCase()
  const href = window.location.href.toLowerCase()
  const evnMap = {
    ali: /evn=ali/,
    boc: /evn=boc/,
    pab: /evn=pab/,
    cib: /evn=cib/,
    icbc: /evn=icbc|icbctime|icbc/,
    ysf: /evn=ysf|ysftime|ysf/,
    efz: /evn=efz|efztime|efz/,
    abc: /evn=abc|abctime|abc/,
    yzf: /evn=yzf|yzf/,
    gat: /evn=gat/,
    sft: /evn=sft|sfttime/,
    cmbc: /evn=cmbccard/,
    test: /evn=test/,
    webview: /webview/
  }
  if (ua.match(/MicroMessenger/i)) evn = "wxWeb"
  Object.entries(evnMap).forEach(([env, regex]) => {
    if (regex.test(href)) evn = env
  })
  evn = window.sessionStorage.getItem("webEvn") || evn
  // #endif
  return evn
}

export function useUrlParams(urlParams = "") {
  let params = {}
  // #ifdef H5
  decodeURIComponent(urlParams || window?.location?.href).replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (params[k] = v))
  // #endif
  // #ifndef H5
  try {
    urlParams = urlParams.replace("?", "") // 去掉可能存在的问号
    const paramPairs = urlParams.split("&")
    for (const pair of paramPairs) {
      const [key, value] = pair.split("=")
      params[key] = value
    }
  } catch (error) {
    params = {}
  }

  // #endif
  return params
}

export function useWindowValue({ key = "", retry = 5, success = () => {}, fail = () => {} }) {
  if (retry > 0) {
    if (window[key]) success(window[key])
    else setTimeout(() => this.useWindowKey({ key, retry: retry - 1, success, fail }), 200)
  } else {
    fail()
  }
}
